package com.shujia.spark.core

import org.apache.spark.{SparkConf, SparkContext}
import org.apache.spark.rdd.RDD

object Demo11ReduceByKey {
  def main(args: Array[String]): Unit = {
    val conf = new SparkConf()

    conf.setAppName("group")

    conf.setMaster("local")

    val sc = new SparkContext(conf)

    //统计学生的总分

    val linesRDD: RDD[String] = sc.textFile("data/score.txt")

    //取出学号和分数
    val scoreRDD: RDD[(String, Int)] = linesRDD
      .map(line => line.split(","))
      .filter(arr => arr.length == 3)
      .map {
        case Array(id: String, _: String, sco: String) =>
          (id, sco.toInt)
      }

    /**
      * groupByKey: 先分组，分组之后对对value进行聚合计算
      *
      */
    scoreRDD
      .groupByKey()
      .map(kv => (kv._1, kv._2.sum))
      .foreach(println)

    /**
      * reduceByKey: 对相同的key的value进行聚合计算， 需要一个聚合函数
      *
      * reduceBykey会在map端进行预聚合，可以减少shuffle过程中需要传输的数据量，效率比GrouByKey高
      * 能使用reducekeyKey的时候尽量使用reduceByKey
      *
      */

    val countRDD: RDD[(String, Int)] = scoreRDD.reduceByKey((x: Int, y: Int) => {
      val j: Int = x + y
      //println(s"$x + $y = $j")
      j
    })

    countRDD.foreach(println)

    while (true) {

    }
  }

}
